package com.witmed.home.view.viewmodel

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.witmed.home.view.intent.VideoIntent
import com.witmed.home.view.resp.VideoRepository
import com.witmed.lib_http.entity.VideoList
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.launch

sealed class VideoState{
    data class Sucess(var list:VideoList):VideoState()
    data class Error(val msg:String):VideoState()
    object Loading:VideoState()
}
class VideoViewModel:ViewModel() {

    val videoResp by lazy { VideoRepository() }

    //创建一个意图管道
    val videoChannel= Channel<VideoIntent>(Channel.UNLIMITED)
    //可变状态的数据流
    private val _videoState= MutableStateFlow<VideoState>(VideoState.Loading)
    //可观察的数据流
    val videoState: StateFlow<VideoState>
        get() = _videoState

    init {
        handlerIntent()
    }

    private fun handlerIntent() {
        viewModelScope.launch {
            videoChannel.consumeAsFlow().collect{
                when(it){
                    is VideoIntent.videoList->
                        videoList(it.page,it.pagesize)
                    is VideoIntent.insetVideo->{
                        videoResp.insetVideo(it.video,it.context)
                        Log.i("===","${it.video.title}新增成功")
                    }

                    else->{}
                }
            }
        }
    }

    private fun videoList(page: Int, pagesize: Int) {
        viewModelScope.launch {
            videoResp.videoList(page, pagesize).collect{
                if(it.code==0){
                    _videoState.value=VideoState.Sucess(it.data!!)
                }else{
                    _videoState.value=VideoState.Error(it.msg)
                }
            }

        }
    }


}